<template>
   
   <el-table :data="bannerList" stripe style="width: 100%" v-loading="loading">
    <el-table-column prop="link" label="轮播图编号" width="180" />
    <el-table-column prop="img" label="轮播图图片" width="180" >
    <template #default="scope">
        <img class="img" :src="scope.row.img" />
      </template>
     </el-table-column>
    <el-table-column prop="alt" label="图片提示" />
    <el-table-column prop="banneris" label="图片链接" />
    <el-table-column prop="boolean" label="是否启用" v-if="crud.charAt(2)==='1'">
        <template #default="scope">
            <el-switch v-model="scope.row.flag" @change="(val:boolean)=>updateBannerFlag(scope.row.bannerid,val)"/>
        </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-popconfirm title="是否删除" @confirm="deleteBannner(scope.row.bannerid)">
          <template #reference>
            <el-button v-if="crud.charAt(3)==='1'">删除</el-button>
          </template>
        </el-popconfirm>
      </template>


    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { reactive,ref } from "vue";
import service from "../../../untils/service";
import { ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';
import {useRoute} from "vue-router";
let loading = ref(true)
const $route = useRoute();
const crud:string = ($route.meta.crud as string);

    interface IBanner {
        link:string,
        img:string,
        alt:string,
        bannerid:string,
        flag:boolean
    }
    // 定义轮播图数据
    let  bannerList = reactive<IBanner[]>([]);
    // 获取轮播图的数据
    const getBannerList = ()=>{
        service({
            url:'/banner/list'
        }).then((res:any)=>{
            if(res.data.code ==='200') {
                bannerList.push(...res.data.data)
                loading.value = false
            }
        })
    }
 
    // 更新获取最新的数据
    const updateBannerFlag=(bannerid:string,val:boolean)=>{
  service({
    url:"/banner/updateFlag",
    method:'post',
    data:{
      bannerid:bannerid,
      flag:val
    }
  }).then(res=>{
    if(res.data.code==="200"){
      
      ElMessage({
        message:'更新成功',
        type:'success'
      })
      
    }
  })
}
    getBannerList();


// 删除单条

const deleteBannner = (bannerid: string) => {

service({
  url: "/banner/delete",
  params: {
    bannerid
  }
}).then(res => {
    if (res.data.code === "200") {
      ElMessage({
        message: '删除成功！',
        type: 'success',
      })

      let index = bannerList.findIndex(item => item.bannerid === bannerid);
      bannerList.splice(index, 1);
    }
  })

}
</script>

<style scoped>
img {
  width: 100px;
  height: 100px;
}
</style>